package com.example.demo.controller;

import com.example.demo.entity.Goods;
import com.example.demo.service.GoodsService;
import com.example.demo.service.serviceimpl.GoodsServiceImpl;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.PostConstruct;
import java.util.LinkedList;
import java.util.List;

@Controller
@ResponseBody
public class GoodsController {

    GoodsService goodsService=new GoodsServiceImpl();

    @PostConstruct
    public void init(){
        this.goodsService=new GoodsServiceImpl();
    }

    @RequestMapping("/goodslist")
    public String goodsList(){
        List<Goods> goods=goodsService.goodsList();
        List<String> list=new LinkedList<>();
        JSONObject jsonObject=new JSONObject();
        for(Goods good:goods){
            JSONObject js=new JSONObject();
            js.put("goodId",good.getGoodId());
            js.put("goodName",good.getGoodName());
            js.put("goodPrice",good.getGoodPrice());
            js.put("goodImageUrl",good.getGoodImageUrl());
            js.put("goodDes",good.getGoodDes());
            list.add(js.toString());
        }
        jsonObject.put("data",list);
        return jsonObject.toString();
    }

    @RequestMapping("/goodscount")
    public String goodsCount(){
        List<Goods> goods=goodsService.goodsList();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("count",goods.size());
        return jsonObject.toString();
    }
}
